package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_LIST;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        /** stringRedisTemplate.opsForList()实现

        //1 redis查询缓存
        String shopTypeString =  stringRedisTemplate.opsForList().leftPop("cache:shopType");
        //1.1 redis没缓存
        if(shopTypeString!=null){
            //1.2 redis有缓存，返回给前端结果
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeString, ShopType.class);

            return Result.ok(shopTypeList);
        }

        //2 查询数据库
        List<ShopType> types = query().orderByAsc("sort").list();
        //2.1 数据库没数据
        if(types==null){
            return Result.fail("无店铺分类");
        }

        //2.2 数据库有数据

        //2.2.1 同步redis缓存
        stringRedisTemplate.opsForList().leftPush("cache:shopType", JSONUtil.toJsonStr(types));
        //2.2.2 返回给前端结果
        return Result.ok(types);
         */

        /**
         * stringRedisTemplate.opsForValue()实现
         */
        //1 redis查询缓存
        String shopTypeString =  stringRedisTemplate.opsForValue().get(SHOP_TYPE_LIST);
        //1.1 redis没缓存
        if(StrUtil.isNotBlank(shopTypeString)){
            //1.2 redis有缓存，返回给前端结果
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeString, ShopType.class);

            return Result.ok(shopTypeList);
        }

        //2 查询数据库
        List<ShopType> types = query().orderByAsc("sort").list();
        //2.1 数据库没数据
        if(types==null){
            return Result.fail("无店铺分类");
        }

        //2.2 数据库有数据

        //2.2.1 同步redis缓存
        stringRedisTemplate.opsForValue().set(SHOP_TYPE_LIST, JSONUtil.toJsonStr(types));
        //2.2.2 返回给前端结果
        return Result.ok(types);
    }
}
